package com.yuyou.fn.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by wens on 2017/3/30.
 */
@Controller
@RequestMapping("/api")
public class QRCodeController {

    @RequestMapping("/qrcode/encode")
    public void qrcodeEncode(@RequestParam("content") String content, HttpServletResponse response) throws WriterException, IOException {
        content = URLDecoder.decode(content,"utf-8");
        int width = 300;
        int height = 300;
        //二维码的图片格式
        String format = "png";
        Map<EncodeHintType, String> hints = new HashMap<>();
        //内容所使用编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);
        BufferedImage image = toBufferedImage(bitMatrix);
        response.setContentType("image/png");
        ImageIO.write(image, format, response.getOutputStream());
    }

    @RequestMapping("/barcode/encode")
    public void barcodeEncode(@RequestParam("content") String content, HttpServletResponse response) throws WriterException, IOException {
        content = URLDecoder.decode(content,"utf-8");
        int width = 400;
        int height = 150 ;
        String format = "png";
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.CODE_128, width, height - 35 , hints);
        BufferedImage image = new BufferedImage(width, height  , BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                image.setRGB(x, y , 0xFFFFFFFF);
            }
        }


        for (int x = 0; x < bitMatrix.getWidth(); x++) {
            for (int y = 0; y < bitMatrix.getHeight(); y++) {
                if(bitMatrix.get(x, y)){
                    image.setRGB(x, y + 10 ,  0xFF000000 );
                }

            }
        }

        StringBuilder sb  = new StringBuilder(100);
        for(int i = 0 ; i < content.length();i += 4 ){
            sb.append(content.substring(i , Math.min( content.length(),i + 4 ) )).append(" ") ;
        }

        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.BLACK);
        graphics.drawString(sb.toString().trim(), image.getWidth() / 2 - 75 , image.getHeight() - 10  );
        graphics.dispose();

        response.setContentType("image/png");
        ImageIO.write(image, format, response.getOutputStream());

    }

    @RequestMapping("/qrcode/encodeBase64")
    @ResponseBody
    public ReturnResult<String> qrcodeEncodeBase64(@RequestParam("content") String content, HttpServletResponse response) throws WriterException, IOException {
        content = URLDecoder.decode(content,"utf-8");
        int width = 120;
        int height = 120;
        //二维码的图片格式
        String format = "png";
        Map<EncodeHintType, String> hints = new HashMap<>();
        //内容所使用编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);
        BufferedImage image = toBufferedImage(bitMatrix);
        // ImageIO.write(image, format, response.getOutputStream());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        String imageString=null;
        try {
            ImageIO.write(image, "png", bos);
            byte[] imageBytes = bos.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //response.setContentType("data:image/png;base64");
        return ReturnResult.success(imageString);

    }

    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

}
